package com.xxx.chat.server.handler;

import com.xxx.chat.message.GroupChatRequestMessage;
import com.xxx.chat.message.GroupChatResponseMessage;
import com.xxx.chat.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * 群消息请求处理handler
 * SimpleChannelInboundHandler<T>可以只监听感兴趣的类型的消息
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        // 根据群名称获取该群所有会话的channel
        List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(msg.getGroupName());
        // 遍历每一个channel，给每一个群成员发送消息
        for (Channel channel : channels) {
            channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), msg.getContent()));
        }
    }
}
